<!--
  系统主页布局
  功能：左侧菜单栏，右侧顶部logo+用户头像，右侧内容区域显示其他页面
-->
<template>
  <div class="home-layout">
    <!-- 左侧菜单栏 -->
    <div class="sidebar">
      <div class="sidebar-header">
        <div class="logo">
          <img :src="logoImage" alt="Logo" @error="handleImageError">
          <span>传奇管理系统</span>
        </div>
      </div>

      <div class="menu-container">
        <div class="menu-list">
          <!-- 顶级菜单 - 仪表盘 -->
          <div class="menu-item menu-item-level-1" :class="{ 'menu-item-active': activeMenu === 'dashboard' }"
            @click="handleMenuClick({ key: 'dashboard', title: '仪表盘', path: '/' })">
            <div class="menu-icon">
              <el-icon>
                <component :is="'Monitor'" />
              </el-icon>
            </div>
            <span class="menu-title">仪表盘</span>
          </div>

          <!-- 二级菜单 - 系统设置 -->
          <div class="menu-item menu-item-level-1"
            :class="{ 'menu-item-active': systemSettingsExpanded, 'menu-item-expanded': systemSettingsExpanded }"
            @click="handleMenuToggle('systemSettings')">
            <div class="menu-icon">
              <el-icon>
                <component :is="'Setting'" />
              </el-icon>
            </div>
            <span class="menu-title">系统设置</span>
            <div class="menu-arrow">
              <el-icon>
                <component :is="systemSettingsExpanded ? 'ArrowDown' : 'ArrowRight'" />
              </el-icon>
            </div>
          </div>

          <!-- 系统设置子菜单 -->
          <div class="submenu" :class="{ 'submenu-expanded': systemSettingsExpanded }">
            <div class="menu-item menu-item-level-2" v-for="submenu in systemSettingsMenus" :key="submenu.key"
              :class="{ 'menu-item-active': activeMenu === submenu.key }" @click="handleMenuClick(submenu)">
              <div class="menu-icon">
                <el-icon>
                  <component :is="submenu.icon" />
                </el-icon>
              </div>
              <span class="menu-title">{{ submenu.title }}</span>
            </div>
          </div>

          <!-- 二级菜单 - 投票管理 -->
          <div class="menu-item menu-item-level-1"
            :class="{ 'menu-item-active': voteManagementExpanded, 'menu-item-expanded': voteManagementExpanded }"
            @click="handleMenuToggle('voteManagement')">
            <div class="menu-icon">
              <el-icon>
                <component :is="'DataLine'" />
              </el-icon>
            </div>
            <span class="menu-title">投票管理</span>
            <div class="menu-arrow">
              <el-icon>
                <component :is="voteManagementExpanded ? 'ArrowDown' : 'ArrowRight'" />
              </el-icon>
            </div>
          </div>

          <!-- 投票管理子菜单 -->
          <div class="submenu" :class="{ 'submenu-expanded': voteManagementExpanded }">
            <div class="menu-item menu-item-level-2" v-for="submenu in voteManagementMenus" :key="submenu.key"
              :class="{ 'menu-item-active': activeMenu === submenu.key }" @click="handleMenuClick(submenu)">
              <div class="menu-icon">
                <el-icon>
                  <component :is="submenu.icon" />
                </el-icon>
              </div>
              <span class="menu-title">{{ submenu.title }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 右侧内容区域 -->
    <div class="main-content">
      <!-- 顶部导航栏 -->
      <div class="top-header">
        <div class="header-left">
          <div class="breadcrumb">
            <el-breadcrumb separator="/">
              <el-breadcrumb-item v-for="item in breadcrumbList" :key="item.key">
                {{ item.title }}
              </el-breadcrumb-item>
            </el-breadcrumb>
          </div>
        </div>

        <div class="header-right">
          <div class="user-info">
            <el-dropdown @command="handleUserCommand">
              <div class="user-avatar-wrapper">
                <el-avatar :size="32" :src="userInfo.avatar" @error="handleAvatarError">
                  {{ userInfo.name.charAt(0) }}
                </el-avatar>
                <span class="user-name">{{ userInfo.name }}</span>
                <el-icon class="arrow-down">
                  <ArrowDown />
                </el-icon>
              </div>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="profile">个人中心</el-dropdown-item>
                  <el-dropdown-item command="settings">系统设置</el-dropdown-item>
                  <el-dropdown-item divided command="logout">退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </div>

      <!-- 内容显示区域 -->
      <div class="content-area">
        <router-view v-slot="{ Component }">
          <transition name="fade" mode="out-in">
            <component :is="Component" />
          </transition>
        </router-view>
      </div>
    </div>
  </div>
</template>

<script setup>
import {
  ref,
  reactive,
  computed,
  onBeforeMount,
  onMounted,
  onBeforeUpdate,
  onUpdated,
  onBeforeUnmount,
  onUnmounted,
  onErrorCaptured,
  nextTick,
  watch
} from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'

// 组件名称
defineOptions({
  name: 'SystemHomeIndex'
})

// 路由
const router = useRouter()
const route = useRoute()

// 响应式变量声明（按照模板中的顺序）
const activeMenu = ref('dashboard')
const systemSettingsExpanded = ref(true)
const voteManagementExpanded = ref(false)
const logoImage = ref('/test.jpg')
const logoMiniImage = ref('/test.jpg')

// 响应式对象
const systemSettingsMenus = reactive([
  {
    key: 'user',
    title: '用户管理',
    icon: 'User',
    path: '/system/user'
  },
  {
    key: 'role',
    title: '角色管理',
    icon: 'UserFilled',
    path: '/system/role'
  }, 
  {
    key: 'menu',
    title: '菜单管理',
    icon: 'Menu',
    path: '/system/menu'
  },
  {
    key: 'auth',
    title: '权限管理',
    icon: 'Key',
    path: '/system/auth'
  },
  {
    key: 'branch',
    title: '分支管理',
    icon: 'Connection',
    path: '/system/branch'
  },
  {
    key: 'module',
    title: '模块管理',
    icon: 'Grid',
    path: '/system/module'
  },
  {
    key: 'token',
    title: '令牌管理',
    icon: 'Key',
    path: '/system/token'
  },
  {
    key: 'record',
    title: '记录管理',
    icon: 'Document',
    path: '/system/record'
  },
  {
    key: 'verify',
    title: '验证管理',
    icon: 'Checked',
    path: '/system/verify'
  },
  {
    key: 'summary',
    title: '系统概览',
    icon: 'DataBoard',
    path: '/system/summary'
  }
])

// 投票管理子菜单
const voteManagementMenus = reactive([
  {
    key: 'voteList',
    title: '投票列表',
    icon: 'List',
    path: '/vote/list'
  },
  {
    key: 'voteRecord',
    title: '投票记录',
    icon: 'Document',
    path: '/vote/record'
  },
  {
    key: 'voteUser',
    title: '投票用户',
    icon: 'User',
    path: '/vote/user'
  },
  {
    key: 'voteEntry',
    title: '投票项管理',
    icon: 'Plus',
    path: '/vote/entry'
  },
  {
    key: 'voteExtra',
    title: '投票额外设置',
    icon: 'Setting',
    path: '/vote/extra'
  }
])

// 为了兼容面包屑导航，保留完整的菜单列表
const menuList = reactive([
  {
    key: 'dashboard',
    title: '仪表盘',
    icon: 'Monitor',
    path: '/'
  },
  ...systemSettingsMenus,
  ...voteManagementMenus
])

const userInfo = reactive({
  name: '管理员',
  avatar: '/test.jpg'
})

const breadcrumbList = reactive([
  {
    key: 'home',
    title: '首页'
  }
])

// 常量定义
const SIDEBAR_WIDTH = 240 // 侧边栏宽度

// 计算属性
const sidebarWidth = computed(() => {
  return SIDEBAR_WIDTH
})

// 响应函数声明（按照模板中的顺序）
/**
 * 菜单点击处理
 */
const handleMenuClick = (menu) => {
  activeMenu.value = menu.key
  router.push(menu.path)
  ElMessage.success(`切换到${menu.title}`)
}

/**
 * 子菜单展开/收起处理
 */
const handleMenuToggle = (menuKey) => {
  // 确保最多只有一个二级菜单展开
  if (menuKey === 'systemSettings') {
    if (systemSettingsExpanded.value) {
      // 如果当前已经展开，则收起
      systemSettingsExpanded.value = false
    } else {
      // 收起其他菜单，展开当前菜单
      systemSettingsExpanded.value = true
      voteManagementExpanded.value = false
    }
  } else if (menuKey === 'voteManagement') {
    if (voteManagementExpanded.value) {
      // 如果当前已经展开，则收起
      voteManagementExpanded.value = false
    } else {
      // 收起其他菜单，展开当前菜单
      voteManagementExpanded.value = true
      systemSettingsExpanded.value = false
    }
  }
}

/**
 * 用户下拉菜单命令处理
 */
const handleUserCommand = (command) => {
  switch (command) {
    case 'profile':
      ElMessage.info('个人中心功能开发中')
      break
    case 'settings':
      ElMessage.info('系统设置功能开发中')
      break
    case 'logout':
      handleLogout()
      break
    default:
      break
  }
}

/**
 * 退出登录处理
 */
const handleLogout = () => {
  ElMessageBox.confirm('确定要退出登录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    try {
      // 首先清除token
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')

      // 显示退出成功提示
      ElMessage.success('退出登录成功')

      // 然后跳转到登录页
      router.push('/login')
    } catch (error) {
      console.error('退出登录时发生错误:', error)
      ElMessage.error('退出登录失败，请重试')
    }
  }).catch(() => {
    // 用户取消操作
  })
}

/**
 * 更新面包屑导航
 */
const updateBreadcrumb = (path) => {
  breadcrumbList.length = 0 // 清空数组

  // 处理仪表盘路径
  if (path === '/' || path === '') {
    breadcrumbList.push({ key: 'dashboard', title: '仪表盘' })
    return
  }

  // 添加首页（仪表盘）作为第一项
  breadcrumbList.push({ key: 'dashboard', title: '首页' })

  // 根据路径查找对应的菜单项
  const menu = menuList.find(item => item.path === path)
  if (menu) {
    breadcrumbList.push({ key: menu.key, title: menu.title })
  } else {
    // 如果找不到对应菜单，尝试从路径中提取模块名称
    const pathSegments = path.split('/').filter(segment => segment)
    if (pathSegments.length > 1) {
      const module = pathSegments[pathSegments.length - 1]
      const moduleMenu = menuList.find(item => item.key === module)
      if (moduleMenu) {
        breadcrumbList.push({ key: moduleMenu.key, title: moduleMenu.title })
      }
    }
  }
}

// 样式函数声明
/**
 * 初始化菜单状态
 */
const initMenuState = () => {
  // 根据当前路由设置激活的菜单
  const currentPath = route.path
  const menu = menuList.find(item => item.path === currentPath)
  if (menu) {
    activeMenu.value = menu.key

    // 根据当前路由自动展开对应的子菜单
    if (currentPath.startsWith('/system/')) {
      systemSettingsExpanded.value = true
      voteManagementExpanded.value = false
    } else if (currentPath.startsWith('/vote/')) {
      voteManagementExpanded.value = true
      systemSettingsExpanded.value = false
    }
  }

  // 更新面包屑
  updateBreadcrumb(currentPath)
}

/**
 * Logo图片加载错误处理
 */
const handleImageError = (event) => {
  // 图片加载失败时，隐藏图片显示
  event.target.style.display = 'none'
  console.warn('Logo图片加载失败，已隐藏图片显示')
}

/**
 * 用户头像加载错误处理
 */
const handleAvatarError = () => {
  // Element Plus的el-avatar组件会自动显示fallback内容（用户名首字母）
  console.warn('用户头像加载失败，显示默认头像')
}

/**
 * 监听路由变化
 */
watch(() => route.path, (newPath) => {
  initMenuState()
})

// 生命周期钩子
onBeforeMount(() => {
  // 组件挂载前执行的逻辑
  console.log('系统主页组件即将挂载')
})

onMounted(() => {
  // 组件挂载后执行的逻辑
  initMenuState()
  console.log('系统主页组件已挂载')
})

onBeforeUpdate(() => {
  // 组件更新之前执行的逻辑
  nextTick(() => {
    // 在DOM更新之后执行的逻辑
  })
})

onUpdated(() => {
  // 组件更新之后执行的逻辑
})

onBeforeUnmount(() => {
  // 组件卸载前执行的逻辑
  console.log('系统主页组件即将卸载')
})

onUnmounted(() => {
  // 组件卸载后执行的逻辑
})

onErrorCaptured((err, instance, info) => {
  // 捕获来自后代组件的错误
  console.error('系统主页组件错误:', err, info)
  return false // 阻止错误继续向上传播
})
</script>

<style lang="less" scoped>
.home-layout {
  display: flex;
  height: 100vh;
  background-color: #f0f2f5;

  // 左侧侧边栏
  .sidebar {
    width: 240px;
    background-color: #001529;
    color: #fff;
    transition: width 0.3s ease;
    display: flex;
    flex-direction: column;
    box-shadow: 2px 0 8px rgba(0, 0, 0, 0.1);
    z-index: 1000;

    // 侧边栏头部
    .sidebar-header {
      height: 64px;
      display: flex;
      align-items: center;
      padding: 0 16px;
      border-bottom: 1px solid rgba(255, 255, 255, 0.1);

      .logo {
        display: flex;
        align-items: center;
        gap: 12px;

        img {
          height: 32px;
          width: auto;
          object-fit: contain;
          border-radius: 4px;

          &.error {
            display: none;
          }
        }

        span {
          font-size: 18px;
          font-weight: 600;
          color: #fff;
          white-space: nowrap;
        }
      }
    }

    // 菜单容器
    .menu-container {
      flex: 1;
      overflow-y: auto;
      padding: 16px 0;

      .menu-list {
        .menu-item {
          display: flex;
          align-items: center;
          padding: 12px 24px;
          margin: 4px 12px;
          border-radius: 8px;
          cursor: pointer;
          transition: all 0.3s ease;
          color: rgba(255, 255, 255, 0.65);
          position: relative;

          &:hover {
            background-color: rgba(255, 255, 255, 0.1);
            color: #fff;
          }

          &.menu-item-active {
            background-color: #1890ff;
            color: #fff;
          }

          // 一级菜单样式
          &.menu-item-level-1 {
            font-weight: 500;
            margin: 8px 12px;

            &.menu-item-expanded {
              color: #fff;
            }

            .menu-icon {
              font-size: 20px;
              margin-right: 12px;
              display: flex;
              align-items: center;
              justify-content: center;
            }

            .menu-arrow {
              position: absolute;
              right: 24px;
              top: 50%;
              transform: translateY(-50%);
              font-size: 14px;
              transition: transform 0.3s ease;
            }
          }

          // 二级菜单样式
          &.menu-item-level-2 {
            padding-left: 48px;
            margin: 2px 12px;
            font-size: 13px;

            &:hover {
              background-color: rgba(24, 144, 255, 0.2);
            }

            &.menu-item-active {
              background-color: #1890ff;
              color: #fff;
            }

            .menu-icon {
              font-size: 16px;
              margin-right: 12px;
              display: flex;
              align-items: center;
              justify-content: center;
            }

            .menu-title {
              font-size: 13px;
              white-space: nowrap;
            }
          }

          .menu-icon {
            font-size: 18px;
            margin-right: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
          }

          .menu-title {
            font-size: 14px;
            white-space: nowrap;
          }
        }

        // 子菜单容器
        .submenu {
          max-height: 0;
          overflow: hidden;
          transition: max-height 0.3s ease;

          &.submenu-expanded {
            max-height: 500px;
            /* 足够大的高度来容纳所有子菜单 */
          }
        }
      }
    }
  }

  // 右侧主内容区域
  .main-content {
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    // background: saddlebrown;

    // 顶部导航栏
    .top-header {
      height: 64px;
      background-color: #fff;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0 24px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
      z-index: 999;

      .header-left {
        display: flex;
        align-items: center;
        gap: 16px;

        .breadcrumb {
          :deep(.el-breadcrumb__item) {
            .el-breadcrumb__inner {
              color: #666;
              font-size: 14px;

              &:hover {
                color: #1890ff;
              }
            }

            &:last-child {
              .el-breadcrumb__inner {
                color: #333;
                font-weight: 500;
              }
            }
          }
        }
      }

      .header-right {
        .user-info {
          .user-avatar-wrapper {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 8px 12px;
            border-radius: 8px;
            cursor: pointer;
            transition: background-color 0.3s ease;

            &:hover {
              background-color: #f0f2f5;
            }

            .user-name {
              font-size: 14px;
              color: #333;
            }

            .arrow-down {
              font-size: 12px;
              color: #666;
            }
          }
        }
      }
    }

    // 内容显示区域
    .content-area {
      flex: 1;
       padding: 10px;
      overflow-y: auto;
      background-color: #e8ecf1;

      // 路由切换动画
      .fade-enter-active,
      .fade-leave-active {
        transition: opacity 0.3s ease;
      }

      .fade-enter-from,
      .fade-leave-to {
        opacity: 0;
      }
    }
  }

  // 响应式设计
  @media (max-width: 768px) {
    .sidebar {
      position: fixed;
      left: 0;
      top: 0;
      height: 100vh;
      z-index: 1001;
    }

    .main-content {
      margin-left: 0;

      .top-header {
        padding: 0 16px;

        .header-left {
          .breadcrumb {
            display: none;
          }
        }
      }

      .content-area {
        padding: 16px;
      }
    }
  }
}
</style>